﻿namespace Vboot.Core.Module.Sys;

public class SysOrgUserService : BaseMainService<SysOrgUser>, ITransient
{
    public SysOrgUserService(SqlSugarRepository<SysOrgUser> repo)
    {
        base.repo = repo;
    }

    public new async Task InsertAsync(SysOrgUser user)
    {
        user.id = YitIdHelper.NextId() + "";
        user.pacod = SecureUtils.PasswordEncrypt(user.pacod);
        if (user.dept != null)
        {
            user.depid = user.dept.id;
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == user.depid).Select(it => it.tier).SingleAsync();
            user.tier = deptTier + user.id + "x";
        }

        repo.Context.Ado.BeginTran();
        await base.InsertAsync(user);
        await repo.Context.Insertable(new SysOrg {id = user.id, name = user.name,type=8}).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }


    public new async Task UpdateAsync(SysOrgUser user)
    {
        if (user.dept != null)
        {
            user.depid = user.dept.id;
            var deptTier = await repo.Context.Queryable<SysOrgDept>()
                .Where(it => it.id == user.depid).Select(it => it.tier).SingleAsync();
            user.tier = deptTier + user.id + "x";
        }

        repo.Context.Ado.BeginTran();
        await base.UpdateAsync(user);
        await repo.Context.Updateable(new SysOrg {id = user.id, name = user.name,type=8})
            .UpdateColumns(it => new {it.name}).ExecuteCommandAsync();
        repo.Context.Ado.CommitTran();
    }

    public async Task ResetPacod(PacodPo po)
    {
        po.pacod = SecureUtils.PasswordEncrypt(po.pacod);
        string sql = "update sys_org_user set pacod=@pacod where id=@id";
        await repo.Context.Ado.ExecuteCommandAsync(sql, new {id = po.id, pacod = po.pacod});

        // await repo.Context.Updateable(new SysOrgUser {id = pacodVo.id, pacod = pacodVo.pacod})
        //     .UpdateColumns(it => new {it.pacod}).ExecuteCommandAsync();
    }
}